package net.gvne.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class ConnectionInfoOpenHandler extends SQLiteOpenHelper {

	private static final String DATABASE = "mwtv";
	private static final int DB_VERSION = 1;

	// CONNECTION TABEL
	private static final String TBL_CONN_INF = "conn_inf";
	private static final String COL_ID = "id";
	private static final String COL_STREAM_ID = "stream_id";
	private static final String COL_MS_URL = "ms_url";
	private static final String COL_USR = "ms_usr";
	private static final String COL_PW = "ms_pw";

	private static final String CREATE_CONN_INF = "CREATE TABLE "
			+ TBL_CONN_INF + " (" + COL_ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_STREAM_ID
			+ " TEXT, " + COL_MS_URL + " TEXT, " + COL_USR + " TEXT, " + COL_PW
			+ " TEXT);";

	public ConnectionInfoOpenHandler(Context context, String name,
			CursorFactory factory, int version) {
		super(context, DATABASE, factory, DB_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_CONN_INF);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	public void insert(String streamId, String msUrl, String msUsr, String msPw) {
		long rowId = -1;
		SQLiteDatabase db = getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(COL_MS_URL, msUrl);
		values.put(COL_PW, msPw);
		values.put(COL_STREAM_ID, streamId);
		values.put(COL_USR, msUsr);
		rowId = db.insert(TBL_CONN_INF, null, values);
	}

	public void update(String streamId, String msUrl, String msUsr, String msPw) {
		int numUpdated;
		SQLiteDatabase db = getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(COL_MS_URL, msUrl);
		values.put(COL_PW, msPw);
		values.put(COL_STREAM_ID, streamId);
		values.put(COL_USR, msUsr);
		numUpdated = db.update(TBL_CONN_INF, values, COL_STREAM_ID + " = ?",
				new String[] { streamId });
	}

	public void read(ConnectionInfo conInf) {
		SQLiteDatabase db = getReadableDatabase();
		String[] cols = { COL_ID, COL_MS_URL, COL_PW, COL_STREAM_ID, COL_USR };
		Cursor cursor = db.query(TBL_CONN_INF, cols, null, null, null, null,
				null);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			conInf.setMsUrl(cursor.getString(1));
			conInf.setMsPw(cursor.getString(2));
			conInf.setStreamId(cursor.getString(3));
			conInf.setMsUsr(cursor.getString(4));
		}

	}
}
